package com.service;

import java.util.HashMap;
import java.util.Map;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;

import com.alibaba.fastjson.JSONObject;
import com.player.WorldMgr;
import com.qy.util.LogUtil;
import com.qy.util.StaticData;

/**
 * 
 * @author Allen
 * @date 2016年12月9日
 *
 */

public final class MsgHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

	public static Map<Integer,ChannelBean> ctxList = new HashMap<Integer,ChannelBean>();
	public static Map<Integer,String> ctxUserMap = new HashMap<Integer,String>();
	public MsgHandler(ChannelGroup group) {
		super();
	}

	/**
	 * 客户端解注册
	 */
	@Override
	public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
	    	LogUtil.warn("用户下线？？？？？？============"+ctxList.size());
	    	remove(ctx.channel());
		super.channelUnregistered(ctx);
	}

	/**
	 * 链接事件触发
	 */
	@SuppressWarnings("deprecation")
	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object msg) throws Exception {
		LogUtil.warn(+ctxList.size()+"=======有人开始连接服务器？？？？？？？？？？？====="+msg);
		// 消息类型满足websocketWebSocket
		if (msg == WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE) {
			ChannelBean tmp = new ChannelBean(ctx);
			ctxList.put(ctx.channel().id().hashCode(), tmp);
			JSONObject js = new JSONObject();
			js.put(StaticData.reKey.code.getKey(), 0);
			// 数据已经满足webSokcet消息头匹配 则清空这个配置
			ctx.pipeline().remove(WebSocketHandler.class);
			ctx.channel().writeAndFlush(new TextWebSocketFrame(js.toJSONString()));
		} else {
			super.userEventTriggered(ctx, msg);
		}
	}

	/**
	 * 收到消息
	 */
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
		JSONObject json = JSONObject.parseObject(msg.text());
		if(json==null){
			json = new JSONObject();
			json.put(StaticData.reKey.code.getKey(), StaticData.codeType.param_error.getType());
			WorldMgr.sendMsg(ctx.channel(), json);
			return;
		}
		getUserId(ctx.channel(),json);
		new GameServerHandler().execute(json, ctx.channel());
	}

	/**
	 * 异常关闭链接且抛出
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.close();
		cause.printStackTrace();
	}
	
	public static void remove(Channel channel){
	    ctxList.remove(channel.id().hashCode());
	    ctxUserMap.remove(channel.id().hashCode());
	}
	
	public static void addChannel(Channel channel,int userId,int type){
	    LogUtil.info(userId+"====channel.id().hashCode()========"+channel.id().hashCode());
	    ctxUserMap.put(channel.id().hashCode(), userId+StaticData.first_split+type);
	}
	
	public static void getUserId(Channel channel,JSONObject param){
	    if(ctxUserMap.containsKey(channel.id().hashCode())){
		String[] tmp = ctxUserMap.get(channel.id().hashCode()).split(StaticData.first_split);
		param.put("userId", tmp[0]);
		param.put("type", tmp[1]);
	    }
	}
//	/**
//	 * 关闭临时的超时的通道
//	 */
//	public static void closeTmpChannel(){
//		long now = TimeUtil.getSysCurSeconds();
//		for(ChannelBean tmp:ctxList.values()){
//			if(now-tmp.getTimeSecond()>=10){
//				JSONObject js = new JSONObject();
//				js.put(StaticData.reKey.code.getKey(), StaticData.codeType.TIME_OUT.getType());
//				tmp.getChannel().channel().writeAndFlush(new TextWebSocketFrame(js.toJSONString()));
//				tmp.getChannel().close();
//				ctxList.remove(tmp.getChannel().channel().id().hashCode());
//			}
//		}
//	}
}